//
//  SACDetailedViewController.m
//  SAP
//
//  Created by 中矿科技有限公司 on 17/9/11.
//  Copyright © 2017年 中矿科技有限公司. All rights reserved.
//

#import "SACDetailedViewController.h"
#import "AgreeViewController.h"
#import "SAProvisionViewController.h"
#import "SAContractMViewController.h"
#import "SATransfertSearchViewController.h"
#import "SAConstractMModel.h"

#import "ActionFlowCell.h"
#import "ContractTermsCell.h"



@interface SACDetailedViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)UIView * viewBtn;
@end

static NSString *const actionCellID =@"ActionFlowCell";
static NSString *const cTermsCellID =@"ContractTermsCell";
@implementation SACDetailedViewController
{
    AFHTTPData *_http;
    NSMutableArray *_sourceData;//流程列表
    NSMutableArray *_actionList;//按钮列表
    NSMutableArray *_nextNodeUserList;
    
    MBProgressHUD *_waitHud;
    ConstractDetailModel *_sourceModel;//详情数据
    NSDictionary *_detailDict;
    
    UIView *_viewBtn;
}

-(UITableView *)tableView{
    if (_tableView) {
        return _tableView;
    }
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-44-8) style:UITableViewStyleGrouped];
    _tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
    [_tableView registerNib:[UINib nibWithNibName:@"ActionFlowCell" bundle:nil] forCellReuseIdentifier:actionCellID];
    [_tableView registerNib:[UINib nibWithNibName:@"ContractTermsCell" bundle:nil] forCellReuseIdentifier:cTermsCellID];
    _tableView.showsVerticalScrollIndicator =NO;
    _tableView.showsHorizontalScrollIndicator =NO;
    _tableView.delegate =self;
    _tableView.dataSource =self;
    return _tableView;
}
-(UIView *)viewBtn{
    if (!_viewBtn) {
        _viewBtn=[[UIView alloc]initWithFrame:CGRectMake(0,SCREEN_HEIGHT-44-64 , SCREEN_WIDTH, 44)];
        [self.view addSubview:_viewBtn];
    }
    return _viewBtn;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _dataArray =[[NSMutableArray alloc]init];
    _actionList =[[NSMutableArray alloc]init];
    _nextNodeUserList =[[NSMutableArray alloc]init];
    _http =[[AFHTTPData alloc]init];
    _sourceData =[[NSMutableArray alloc]init];

    [_dataArray addObjectsFromArray: @[@"基本信息",@"收货信息",@"价格信息",@"收买人信息",@"出卖人信息",@"合同条款",@"操作流程"]];
    
    [self customUI];
    [self prepareData];
}

-(void)prepareData{
    if(!_waitHud)_waitHud=[[MBProgressHUD alloc] initWithView:self.view];//加载
    [self.view addSubview:_waitHud];
    // _waitHud.mode = MBProgressHUDModeText;
   [_waitHud showAnimated:YES];
    NSString *strUrl =[NSString stringWithFormat:SAPContractDetailKUrl,self.controllerId];
    [_http postTokenDataWithUrl:strUrl httpBobyData:nil onSuccess:^(NSData *data) {

        _detailDict =[ConstractDetailModel getGetOptionsDetailDictfromData:data];
        
        _sourceModel =[ConstractDetailModel getGetOptionsDetailfromData:data];
        
        NSArray *array =[SAflowInstanceHistoryList getOptionsFlowDetailfromData:data];
        [_sourceData removeAllObjects];
        [_sourceData addObjectsFromArray:array];
        
        NSArray *array1 =[SAActionList getOptionsAcstionListfromData:data];
        [_actionList removeAllObjects];
        [_actionList addObjectsFromArray:array1];
        
        NSArray *array2 =[SANextNodeUserList getOptionsNextNodeUserListfromData:data];
        [_nextNodeUserList addObjectsFromArray:array2];
        
        if ((_sourceModel.contract.contractStatus.integerValue ==1 || _sourceModel.contract.contractStatus.integerValue ==3) && [[[UserManager sharedInstance] getUserId].description isEqualToString:_sourceModel.contract.userId.description] ) {
            [self creatRightItem];
        }else{
            self.navigationItem.rightBarButtonItem =nil;
        }
        if(_actionList.count>0 )[self creatBtn];
        if (_actionList.count ==0 ) {
            self.tableView.frame =CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64);
            [_viewBtn removeFromSuperview];
        }
        [_tableView reloadData];
        [_waitHud showAnimated:NO];
        [_waitHud hideAnimated:YES];
    } onFailure:^(NSError *error) {
        [_waitHud showAnimated:NO];
        [_waitHud hideAnimated:YES];
    }];
}

-(void)creatBtn{
    float btnHight =0;
    float btnwight =SCREEN_WIDTH/_actionList.count;
//    if (_sourceModel.contract.contractStatus.integerValue ==1 || _sourceModel.contract.contractStatus.integerValue ==3){
//        for (SAActionList * model in _actionList) {
//            if ([model.actionCode isEqualToString:@"ContractFlow.Apply.Apply"]) {
//                UIButton *submitBtn =[UITool btnWithTitle:[_actionList[1] actionName] frame:CGRectMake(0,btnHight, SCREEN_WIDTH,44) font:[UIFont systemFontOfSize:17] unselectColor:[UIColor colorFromHex:@"333333"] backColor:[UIColor whiteColor]];
//                [submitBtn addTarget:self action:@selector(onClickedBtn:) forControlEvents:UIControlEventTouchUpInside];
//                [self.viewBtn addSubview:submitBtn];
//                return;
//            }
//        }
//
//    }
    
    for (NSInteger i =0; i<_actionList.count; i++) {
        
        if([[_actionList[i] actionCode] isEqualToString:@"ContractFlow.Apply.Save"]) continue;
        if ([[_actionList[i] actionCode] isEqualToString:@"ContractFlow.Apply.Apply"] ) {
            UIButton *submitBtn =[UITool btnWithTitle:[_actionList[i] actionName] frame:CGRectMake(0,btnHight, SCREEN_WIDTH,44) font:[UIFont systemFontOfSize:17] unselectColor:[UIColor colorFromHex:@"333333"] backColor:[UIColor whiteColor]];
            [submitBtn addTarget:self action:@selector(onClickedBtn:) forControlEvents:UIControlEventTouchUpInside];
            [self.viewBtn addSubview:submitBtn];
            return;
        }
        
        
        UIButton *submitBtn =[UITool btnWithTitle:[_actionList[i] actionName] frame:CGRectMake(btnwight*i,btnHight, btnwight-1,44) font:[UIFont systemFontOfSize:17] unselectColor:[UIColor colorFromHex:@"333333"] backColor:[UIColor whiteColor]];
        [submitBtn addTarget:self action:@selector(onClickedBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self.viewBtn addSubview:submitBtn];
        if(_actionList.count >1){
            UILabel *lineLabel =[UITool labelWithTitle:@"" frame:CGRectMake(btnwight*(i+1), 4, 1, 30) font:[UIFont systemFontOfSize:11] textColor:[UIColor whiteColor] backColor:[UIColor colorFromHex:@"666666"]];
            [self.viewBtn addSubview:lineLabel];
        }
    }
}

-(void)onClickedBtn:(UIButton *)sender{
    NSString *actionCode;
    NSString *nextUserID =@"0";
    if(_nextNodeUserList.count>0) nextUserID =[_nextNodeUserList[0] Id];
    for (SAActionList *model in _actionList) {
        if ([model.actionName isEqualToString:sender.titleLabel.text]) {
            actionCode =model.actionCode;
        }
    }
    AgreeViewController *agreeVC=[[AgreeViewController alloc]init];
    agreeVC.completion =^(id userInfo, AgreeViewController *bVC){
        [self prepareData];
    };
    agreeVC.SAApprovalStatusType =SAApprovalContract;
    agreeVC.nextNodeUserList =_nextNodeUserList;
    agreeVC.actionCode =actionCode;
    //agreeVC.nextUserID =nextUserID;
    agreeVC.detailDict =_detailDict;
    agreeVC.navtitle =sender.titleLabel.text;


    [self.navigationController pushViewController:agreeVC animated:NO];

#if 0
        NSString *strUrl =[NSString stringWithFormat:SAPExecuteActionKUrl,actionCode,nextUserID,@""];
        [_http postTokenDataWithUrl:strUrl httpBobyData:_detailDict onSuccess:^(NSData *data) {
            
                NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",dict);
            [MBProgressHUD showSuccess:[NSString stringWithFormat:@"合同%@成功",sender.titleLabel.text]];
            !self.completion ?: self.completion(nil, self);
            [self.navigationController popViewControllerAnimated:NO];
        } onFailure:^(NSError *error) {
            [MBProgressHUD showSuccess:[NSString stringWithFormat:@"合同%@失败",sender.titleLabel.text]];
        }];
#endif

}

-(void)creatRightItem{
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(onClickedDelItem)];
}

-(void)customUI{
    self.view.backgroundColor =SA_AllBackColor;
    self.navigationItem.title =@"合同详情";

    [self.view addSubview:self.tableView];
}



-(void)onClickedDelItem{
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"删除" message:@"确定删除该合同" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *OKAction  = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSString *str =[NSString stringWithFormat:SAPContractDeleteKUrl,_sourceModel.contract.Id];
        [_http getDataWithUrl:str onSuccess:^(NSData *data) {
            NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",dict);
            [MBProgressHUD showSuccess:@"合同删除成功"];
            !self.completion ?: self.completion(nil, self);
            [self.navigationController popViewControllerAnimated:NO];
        } onFailure:^(NSError *error) {
            [MBProgressHUD showSuccess:@"合同删除失败"];
        }];
    }];
    UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //  NSLog(@"点击了取消");
    }];
    
    [alertVC addAction:OKAction];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];

}

-(void)onClickedTemsMore:(NSString *)str{
    SAProvisionViewController * provsionVC =[[SAProvisionViewController alloc]initWithNibName:@"SAProvisionViewController" bundle:nil];

    provsionVC.navTitle =@"合同条款";
    provsionVC.provisionStr =str;
    [self.navigationController pushViewController:provsionVC animated:NO];
}


#pragma mark tableView-Delegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        return 8;
    }else if (section ==1){
        return 6;
    }else if (section ==2){
        return 4;
    }else if (section>2 && section<=4){
        return 9;
    }else if (section ==5){
        return 2;
    }
    return _sourceData.count;
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section<6 ) {
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cellID"];
        if (!cell) {
            cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"];
        }
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        cell.textLabel.textColor =[UIColor colorFromHex:@"666666"];
        //基本信息
        if (indexPath.section == 0) {
            if(indexPath.row ==0) cell.textLabel.text =[NSString stringWithFormat:@"合同编号: %@",_sourceModel.contract.contractCode.description];
            if(indexPath.row ==1) cell.textLabel.text =[NSString stringWithFormat:@"签订日期: %@",_sourceModel.contract.signDate];
            if(indexPath.row ==2) cell.textLabel.text =[NSString stringWithFormat:@"合同类型: %@",_sourceModel.contractTypeName];
            if(indexPath.row ==3) cell.textLabel.text =[NSString stringWithFormat:@"签订地点: %@",_sourceModel.contract.signPlace];
            if(indexPath.row ==4) cell.textLabel.text =[NSString stringWithFormat:@"有效期: %@-%@",_sourceModel.startDateString,_sourceModel.endDateString];
            if(indexPath.row ==5) cell.textLabel.text =[NSString stringWithFormat:@"负责人: %@",_sourceModel.adminName];
            if(indexPath.row ==6){
                cell.textLabel.text =[NSString stringWithFormat:@"购销总金额: %@",_sourceModel.contract.totalAmountString];
//                cell.textLabel.textColor =[UIColor colorFromHex:
//                                           @"15A7FE"];
            }
            
            if(indexPath.row ==7){
                cell.textLabel.text =[NSString stringWithFormat:@"合同总量: %@",_sourceModel.contract.totalNumberString];
                cell.textLabel.textColor =[UIColor colorFromHex:
                                           @"15A7FE"];
            }
        }
        //收货信息
        if (indexPath.section == 1) {
            if(indexPath.row ==0) cell.textLabel.text =[NSString stringWithFormat:@"收货单位: %@",_sourceModel.receipt.receivingUnit];
            if(indexPath.row ==1) cell.textLabel.text =[NSString stringWithFormat:@"运输方式: %@",_sourceModel.transportType];
            if(indexPath.row ==2) cell.textLabel.text =[NSString stringWithFormat:@"省   市: %@",_sourceModel.receipt.receivingAddress];
            if([UITool isBlankString:_sourceModel.sendStation])_sourceModel.sendStation =@"- -";
            if([UITool isBlankString:_sourceModel.targetStation])_sourceModel.targetStation =@"- -";
            if(indexPath.row ==3) cell.textLabel.text =[NSString stringWithFormat:@"发   站: %@",_sourceModel.sendStation];
            if(indexPath.row ==4) cell.textLabel.text =[NSString stringWithFormat:@"到   站: %@",_sourceModel.targetStation];
            if(indexPath.row ==5) cell.textLabel.text =[NSString stringWithFormat:@"办事处: %@",_sourceModel.office];
        }
        //价格信息
        if (indexPath.section == 2) {
            if(indexPath.row ==0) cell.textLabel.text =[NSString stringWithFormat:@"价   格: %@",_sourceModel.receipt.price];
            if(indexPath.row ==1) cell.textLabel.text =[NSString stringWithFormat:@"品   种: %@",_sourceModel.variety];
            if(indexPath.row ==2) cell.textLabel.text =[NSString stringWithFormat:@"价格类型: %@",_sourceModel.priceType];
            if(indexPath.row ==3) cell.textLabel.text =[NSString stringWithFormat:@"质量指标: %@",_sourceModel.receipt.qualityIndex ?_sourceModel.receipt.qualityIndex:@"" ];
        }
        //收买人信息
        if (indexPath.section == 3) {
            if(indexPath.row ==0) cell.textLabel.text =[NSString stringWithFormat:@"单位名称: %@",_sourceModel.buyer.name];
            if(indexPath.row ==1) cell.textLabel.text =[NSString stringWithFormat:@"地   址: %@",_sourceModel.buyer.address];
            if(indexPath.row ==2) cell.textLabel.text =[NSString stringWithFormat:@"法定代表: %@",_sourceModel.buyer.legalPerson];
            if(indexPath.row ==3) cell.textLabel.text =[NSString stringWithFormat:@"委托代表: %@",_sourceModel.buyer.principalAgent];
            if(indexPath.row ==4) cell.textLabel.text =[NSString stringWithFormat:@"开户银行: %@",_sourceModel.buyer.bank];
            if(indexPath.row ==5) cell.textLabel.text =[NSString stringWithFormat:@"银行账号: %@",_sourceModel.buyer.bankAccount];
            if(indexPath.row ==6) cell.textLabel.text =[NSString stringWithFormat:@"纳税登记号: %@",_sourceModel.buyer.taxRegNumber];
            if(indexPath.row ==7) cell.textLabel.text =[NSString stringWithFormat:@"邮政编码: %@",_sourceModel.buyer.zipCode];
            if(indexPath.row ==8) cell.textLabel.text =[NSString stringWithFormat:@"联系电话: %@",_sourceModel.buyer.phone];
        }
        
        //出卖人信息
        if (indexPath.section == 4) {
            if(indexPath.row ==0) cell.textLabel.text =[NSString stringWithFormat:@"单位名称: %@",_sourceModel.seller.name];
            if(indexPath.row ==1) cell.textLabel.text =[NSString stringWithFormat:@"地   址: %@",_sourceModel.seller.address];
            if(indexPath.row ==2) cell.textLabel.text =[NSString stringWithFormat:@"法定代表: %@",_sourceModel.seller.legalPerson];
            if(indexPath.row ==3) cell.textLabel.text =[NSString stringWithFormat:@"委托代表: %@",_sourceModel.seller.principalAgent];
            if(indexPath.row ==4) cell.textLabel.text =[NSString stringWithFormat:@"开户银行: %@",_sourceModel.seller.bank];
            if(indexPath.row ==5) cell.textLabel.text =[NSString stringWithFormat:@"银行账号: %@",_sourceModel.seller.bankAccount];
            if(indexPath.row ==6) cell.textLabel.text =[NSString stringWithFormat:@"纳税登记号: %@",_sourceModel.seller.taxRegNumber];
            if(indexPath.row ==7) cell.textLabel.text =[NSString stringWithFormat:@"邮政编码: %@",_sourceModel.seller.zipCode];
            if(indexPath.row ==8) cell.textLabel.text =[NSString stringWithFormat:@"联系电话: %@",_sourceModel.seller.phone];
        }
        if (indexPath.section == 5) {
            if(indexPath.row ==0) cell.textLabel.text =@"合同条款详情";
            if(indexPath.row ==1) cell.textLabel.text =[NSString stringWithFormat:@"已调拨: %@",_transferCount];
//            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:cell.textLabel.text];
//            NSRange strRange = {0,[str length]};
//            [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
//            cell.textLabel.attributedText = str;
            cell.textLabel.textColor =[UIColor colorFromHex:@"15A7FE"];
        }
        
        return cell;
    }
//    else if (indexPath.section==5){
//        ContractTermsCell *cell =[tableView dequeueReusableCellWithIdentifier:cTermsCellID forIndexPath:indexPath];
//        [cell setFromContractTermsModel:_sourceModel.provision];
//        [cell.temsMoreBtn addTarget:self action:@selector(onClickedTemsMore:) forControlEvents:UIControlEventTouchUpInside];
//        cell.selectionStyle =UITableViewCellSelectionStyleNone;
//        return cell;
//    }
    else{
        ActionFlowCell *cell =[tableView dequeueReusableCellWithIdentifier:actionCellID forIndexPath:indexPath];
        [cell setFromContractTermsModel:_sourceData[indexPath.row]];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        return cell;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    UILabel *label =[[UILabel alloc]initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH, 44)];
    label.backgroundColor =SA_AllBackColor;
    label.textColor =[UIColor colorFromHex:@"333333"];
    label.text =_dataArray[section];
    [headView addSubview:label];
    return headView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==6) {
        return 80;
    }else if(indexPath.section ==5){
        return 40;
    }else{
        return 40;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section ==0 && indexPath.row ==7) {
        SAContractMViewController *saContractMVC =[[SAContractMViewController alloc]init];
        
        saContractMVC.monthPlans =(NSMutableArray *)[SAConstractMModel getConstractMfromData:_sourceModel.monthPlan];
        [self.navigationController pushViewController:saContractMVC animated:NO];
    }
    //流程审批
    if (indexPath.section ==_dataArray.count-1) {
        SAProvisionViewController * provsionVC =[[SAProvisionViewController alloc]initWithNibName:@"SAProvisionViewController" bundle:nil];
        provsionVC.provisionStr =[NSString stringWithFormat:@"备注:\n\t%@", [_sourceData[indexPath.row] remark] ?[_sourceData[indexPath.row] remark]:@"" ];
        provsionVC.navTitle =[_sourceData[indexPath.row] nodeDisplayName];
        [self.navigationController pushViewController:provsionVC animated:NO];
    }
    
    //合同条款
    if (indexPath.section == _dataArray.count -2) {
        SAProvision *model = _sourceModel.provision;
        if (indexPath.row == 0) [self onClickedTemsMore:[NSString stringWithFormat:@"质量和数量验收标准及方式:\n  %@\n煤炭单价及执行期:\n  %@\n货款及运杂费结算方式:\n  %@\n违约责任:\n  %@\n解决合同纠纷的方式:\n  %@\n其他约定事项:\n  %@",model.acceptanceCriteria,model.priceExecutionPeriod,model.settlementMethod,model.breachContract,model.resolveDispute,model.other]];
        if (indexPath.row == 1){
            if( _transferCount.integerValue ==0) {
                [MBProgressHUD showSuccess:@"该合同暂无调拨单"];
               
            }else{
            SATransfertSearchViewController *saTransferSVC =[[SATransfertSearchViewController alloc]init];
            saTransferSVC.contractId =_sourceModel.contract.Id.description;
                [self.navigationController pushViewController:saTransferSVC animated:NO];
            }
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
